package com.test.action;

import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @Author: LiuYuanQi
 * @Date: 2020/5/22 10:04
 */
public class TestPthon {

    public static void main(String[] args){
        String pythonPath = "F:/gitPythonRepository/als-python/HelloWord.py";
//        helloWorld(pythonPath);
        add(pythonPath);
    }

    private static void helloWorld(String pythonPath){
        try {
            String[] args1=new String[]{"python", pythonPath, "123"};
            Process pr=Runtime.getRuntime().exec(args1);

            BufferedReader in = new BufferedReader(new InputStreamReader(
                    pr.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            pr.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void add(String pythonPath) {
        PythonInterpreter interpreter = new PythonInterpreter();
            interpreter.execfile(pythonPath);

        // 第一个参数为期望获得的函数（变量）的名字，第二个参数为期望返回的对象类型
        PyFunction pyFunction = interpreter.get("add", PyFunction.class);
        int a = 5, b = 10;
        //调用函数，如果函数需要参数，在Java中必须先将参数转化为对应的“Python类型”
        PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b));
        System.out.println("the anwser is: " + pyobj);
    }

}
